import { getStaffsApi } from "@/api/staff";
import MyCard from "@/components/card"
import AuthButton from "@/hoc/auth-button/Auth-button";
import useFindData from "@/hooks/useFindData";
import { PlusOutlined } from "@ant-design/icons"
import { Button, Input, Select, Space, DatePicker, Table } from "antd"
import type { SearchProps } from "antd/es/input";
import type { TableProps } from "antd/lib";
import { useEffect, useRef, useState } from "react";
import { useNavigate } from "react-router";
import { utils, writeFile } from "xlsx";


interface DataType {
    avatar: string,
    name: string,
    phone: string,
    IDNumber: string,
    workplace: string,
    education: string,
    graduateSchool: string,
    birthday: string,
    entryDate: string,
    department: string,
    job: string,
    position: string,
    rank: string,
    state: string,

}
const fixedColumns: TableProps<DataType>['columns'] = [

    {
        title: '头像/姓名',
        render: (item) => (
            <Space size="middle">
                {/* <img src={item.avatar} /> */}
                <span>{item.name}</span>
            </Space>
        ),
    },
    {
        title: '工号',
        dataIndex: 'workNumber'
    },
    {
        title: '部门',
        dataIndex: 'organizationIds',
    },
    {
        title: '职位',
        dataIndex: 'job',
    },
    {
        title: '类型',
        dataIndex: 'state',
        render: (item) => (
            <Space size="middle">
                <span>{getState(item)}</span>
            </Space>
        )
    },
    {
        title: '证件类型',
        render: () => (
            <span>身份证</span>
        )
    },
    {
        title: '身份证号',
        dataIndex: 'IDNumber'
    },
    {
        title: '入职时间',
        dataIndex: 'entryDate',
    },

];

const getState = (data: string) => {
    if (data == '1') {
        return '试用'
    } else if (data == '2') {
        return '正式'
    } else if (data == '3') {
        return '待离职'
    } else if (data == '4') {
        return '已离职'
    } else if (data == '5') {
        return '待入职'
    } else {
        return '暂无'
    }
}








const StaffRoster = () => {
    const [searchData, setSearchData] = useState({ searchValue: '' });
    const { RangePicker } = DatePicker;
    const [staffData, setStaffData] = useState({ rows: [], total: 0 });
    const [pageData, setPageData] = useState({ currentPage: 1, pageSize: 10 })
    const { getJobsHook, jobsData, getPositionsHook, positionsData, getRanksHook, ranksData,
        getWorkPlaceHook, workplaceData,
        getOrganization, organizationData

    } = useFindData();
    const choseCheckBoxData = useRef<React.Key[]>([]);
    const navigate = useNavigate();

    //表单额外列配置
    const columns: TableProps<DataType>['columns'] = [
        ...fixedColumns, {
            title: '操作',
            key: 'action',
            width: 120,
            render: () => (
                <Space size="middle">
                    <a onClick={() => {
                        // formRef.current!.onOpenForm(item);
                    }
                    }>编辑</a>
                    <a onClick={() => {
                        // showConfirm(item._id)
                    }}>删除</a>
                </Space>
            ),
        },

    ];

    console.log(getExcelData(staffData.rows));


    useEffect(() => {
        //职务
        getJobsHook();
        //职位
        getPositionsHook();
        //职级
        getRanksHook();
        //工作地点
        getWorkPlaceHook();
        //部门
        getOrganization();
    }, [])

    useEffect(() => {
        getStaffs();
    }, [pageData])
    //分页
    const changePageData = (currentPage: number, pageSize: number) => {
        setPageData({ currentPage, pageSize })
    }

    //多选框
    const onChoseCheckBox = (selectedRowKeys: any) => {
        choseCheckBoxData.current = selectedRowKeys
    }
    //搜索框
    const onSearch: SearchProps['onSearch'] = (value) => {
        setSearchData({ searchValue: value })
    };
    //获取
    const getStaffs = () => {
        getStaffsApi({
            ...pageData,
            searchData,
        }).then(res => {
            if (res.code == 200) {
                setStaffData(res.data)
            }
        })
    }
    const titleTopInfo = [
        { name: '在职', number: 100 },
        { name: '试用', number: 10 },
        { name: '正式', number: 80 },
        { name: '待离职', number: 80 },
        { name: '已离职', number: 20 },
        { name: '待入职', number: 8 },
    ]
    return (
        <>
            <MyCard title='花名册'>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 20, color: "#999999" }}>
                    <>
                        <Space>
                            <span>职位</span><Select style={{ width: 200 }} options={positionsData.rows} fieldNames={{
                                label: 'name', value: 'name',
                            }}></Select>
                        </Space>
                        <Space>
                            <span>职务</span><Select style={{ width: 200 }} options={jobsData.rows} fieldNames={{
                                label: 'name', value: 'name',
                            }}></Select>
                        </Space>
                        <Space>
                            <span>职级</span><Select style={{ width: 200 }} options={ranksData.rows} fieldNames={{
                                label: 'name', value: 'name',
                            }}></Select>
                        </Space>
                    </>
                    <Space>
                        <AuthButton type="primary" icon={<PlusOutlined />} onClick={() => { navigate('/staff/staffManage/staffManage/add') }}>
                            添加员工
                        </AuthButton>
                        <Button color="primary" variant="outlined">导入</Button>
                        <Button color="primary" variant="outlined">导出</Button>
                        <Button color="primary" variant="outlined">更多操作</Button>
                    </Space>
                </div>
                <div style={{ color: '#999999' }}>
                    <Space size={'large'}>
                        <Space style={{ marginRight: 4 }}>
                            <span>部门</span><Select style={{ width: 200 }} options={organizationData.rows} fieldNames={{
                                label: 'name', value: 'name',
                            }}></Select>
                        </Space>
                        <Space>
                            <span>工作地点</span><Select style={{ width: 200 }} options={workplaceData.rows} fieldNames={{
                                label: 'name', value: 'name',
                            }}></Select>
                        </Space>
                        <Space style={{ marginLeft: 5 }}>
                            <span>选择日期</span>
                            <RangePicker
                                showTime={{ format: 'HH:mm' }}
                                format="YYYY-MM-DD HH:mm"
                                onChange={(value, dateString) => {
                                    console.log('Selected Time: ', value);
                                    console.log('Formatted Selected Time: ', dateString);
                                }}
                                style={{ width: 260 }}
                            // onOk={onOk}
                            />
                        </Space>
                        <Input.Search placeholder="请输入关键字" style={{ width: 300 }} allowClear onSearch={onSearch} />
                    </Space>
                </div>
                <div style={{ marginTop: 20, marginBottom: 20, display: 'flex' }}>
                    <Space>
                        {titleTopInfo.map(item => {
                            return (
                                <div style={{
                                    width: 195, height: 90, border: '1px solid #e0dbdbff',
                                    borderRadius: 6, flexDirection: 'column', boxShadow: '0px 0px 3px 3px rgba(208, 233, 236, 0.2)'
                                }}
                                    className="flex-ct">
                                    <span style={{ color: '#999999', fontSize: 13 }}>{item.name}</span>
                                    <div style={{ fontSize: 20 }}>{item.number}</div>
                                </div>

                            )
                        })}
                    </Space>

                </div>
                <Table<DataType> columns={columns} dataSource={staffData.rows} rowKey="_id" rowSelection={{ onChange: onChoseCheckBox }}
                    pagination={{
                        total: staffData.total,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        showTotal: (total) => `总计 ${total} 条数据`,
                        pageSizeOptions: [2, 5, 10, 20, 50],
                        onChange: changePageData
                    }} />
            </MyCard>
        </>
    )
}

export default StaffRoster

function getExcelData(data: any) {
    // console.log(data);
    const temp = data.map(item => [item.name, item.phone, item.education]
    )
    return [
        ['姓名', '电话', '学历'],
        ...temp
    ]
}


function onExport(data: []) {
    //导出数据
    // excel文件中的工作表
    const sheet = utils.aoa_to_sheet(data);
    // 创建一个excel文件
    const book = utils.book_new();
    // 将工作表添加到excel文件中
    utils.book_append_sheet(book, sheet, '表1');
    writeFile(book, '员工信息表.xlsx');

}